package com.ys.shop.control;

import com.ys.shop.dao.GoodDAOImp;
import com.ys.shop.dao.IDAO;
import com.ys.shop.util.ShoppingCarUtil;
import com.ys.shop.vo.Product;
import com.ys.shop.vo.ShoppingCarGood;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "ShoppingCarServlet")
public class ShoppingCarServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1、获取网页所发来的id值
        int id=Integer.parseInt(request.getParameter("id"));
        //2、获取商品数据
        IDAO idao=new GoodDAOImp();
        Product product=((GoodDAOImp) idao).getGoodByID(id);
        //3、将数据放入购物车      List集合     购物车只有一台
        List shoppinglist=null;//购物车
        if(shoppinglist==null){
            shoppinglist=new ArrayList<ShoppingCarGood>();
        }

        ShoppingCarGood shoppingCarGood =new ShoppingCarGood();
        shoppingCarGood.setId(product.getEp_id());
        shoppingCarGood.setName(product.getEp_name());
        shoppingCarGood.setPrice(product.getEp_price());
        shoppingCarGood.setNum(1);
        shoppingCarGood.setEp_file_name(product.getEp_file_name());

        //将商品添加到购物车(如果是第一次添加一个商品，如果多次添加只要把数量加一)
        ShoppingCarUtil.addGood(shoppingCarGood,shoppinglist);
        HttpSession session=request.getSession();
        session.setAttribute("shop",shoppinglist);
        request.getRequestDispatcher("ShoppingCar.jsp").forward(request,response);




    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
